﻿using System;
using System.Configuration;
using System.IO;

namespace LMS.DocumentConvertService
{
    public class ServiceHandle
    {
        private readonly ServiceListener listener;

        public ServiceHandle()
        {
            listener = new ServiceListener();
        }

        public void Start()
        {
            listener.Start();
            
            if (ConfigurationManager.AppSettings["AutoConvertInputFoldFiles"] == "1")
            {
                //自动转换Input目录下的文件
                System.Threading.ThreadPool.QueueUserWorkItem((o) =>
                {
                    convertInputFoldToPdf();
                });
            }
        }

        public void Stop()
        {
            listener.Stop();
            
            LogWriter.Instance.Flush();
        }

        private void convertInputFoldToPdf()
        {
            #region 自动转换Input目录下的文件到Output目录

            LogHelper.Info<ServiceListener>("convertInputFoldToPdf Start");
            var inputFold = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Input");

            if (Directory.Exists(inputFold))
            {
                var outputFold = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Output");
                if (!Directory.Exists(outputFold))
                {
                    Directory.CreateDirectory(outputFold);
                }

                foreach (var path in Directory.GetFiles(inputFold))
                {
                    if (Path.GetFileName(path).StartsWith("~$"))
                    {
                        //临时文件
                        continue;
                    }
                    var targetPath = Path.Combine(outputFold, Path.GetFileName(path) + ".pdf");

                    if (File.Exists(targetPath) == false)
                    {
                        try
                        {
                            ConvertHelper.ConvetToPdf(path, targetPath);
                        }
                        catch (Exception ex)
                        {
                            LogHelper.Error<ServiceListener>(ex, "convertInputFoldToPdf {0} Error", Path.GetFileName(path));
                        }
                    }
                }
            }

            LogHelper.Info<ServiceListener>("convertInputFoldToPdf Finish");
            #endregion 自动转换Input目录下的文件到Output目录
        }
    }
}